package com.taotao.service.Impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.service.PictureService;
import com.taotao.common.utils.FtpUtil;
import com.taotao.common.utils.IDUtils;

@Service
public class PictureServiceImpl implements PictureService {
	
	//FTP服务器配置
	@Value("${FTP_ADDRESS}")
	String FTP_ADDRESS;
	@Value("${FTP_PORT}")
	String FTP_PORT;
	@Value("${FTP_USERNAME}")
	String FTP_USERNAME;
	@Value("${FTP_PASSWORD}")
	String FTP_PASSWORD;
	@Value("${FTP_BASEPATH}")
	String FTP_BASEPATH;

	//图片服务器配置
	@Value("${IMAGE_ADDRESS}")
	String IMAGE_ADDRESS;	
	
	 @SuppressWarnings("unchecked")
	public Map uploadFile(MultipartFile multipartFile){
		 InputStream orginInputStream;
		 @SuppressWarnings("rawtypes")
		Map map=new HashMap();
		try {
			orginInputStream = multipartFile.getInputStream();
			 String filepath=new DateTime().toString("/yyyy/MM/dd");
			 String originalFilename = multipartFile.getOriginalFilename();
			 String fileSuffix=originalFilename.substring(originalFilename.lastIndexOf('.'));
			 String filename=IDUtils.genImageName()+fileSuffix;
			 
			 boolean ok=FtpUtil.uploadFile(FTP_ADDRESS, Integer.parseInt(FTP_PORT), FTP_USERNAME, FTP_PASSWORD, FTP_BASEPATH
					 , filepath, filename, orginInputStream);
			 if(ok) {
				 map.put("error", 0);
				 String url="http://"+IMAGE_ADDRESS+"/images"+filepath+"/"+filename;
				 map.put("url", url);
			 }
			 else {
				 map.put("error", 1);
				 map.put("message","上传失败！");
			 }
			 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		 return map;

	}
	 
}
